package scatter.file.rest.cloudstorage.service.impl;

import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import scatter.common.rest.exception.BusinessException;
import scatter.common.rest.service.IDeleteServiceListener;
import scatter.common.rest.tools.InterfaceTool;
import scatter.file.pojo.po.File;
import scatter.file.rest.cloudstorage.service.ApiCloudStorageService;

import java.util.List;

/**
 * 删除文件对象
 * Created by yangwei
 * Created at 2020/12/17 10:06
 */
@Slf4j
@Component
public class CloudStorageFileDeleteServiceListenerImpl implements IDeleteServiceListener<File>, InterfaceTool {
    @Autowired
    private List<ApiCloudStorageService> apiCloudStorageServices;
    @Override
    public void preDeleteById(String id, File file) {

    }

    @Override
    public void postDeleteById(String id, File file) {

        deleteObject(newArrayList(file));
    }

    @Override
    public void preDeleteByColumn(String columnId, SFunction<File, ?> column, List<File> files) {

    }

    @Override
    public void postDeleteByColumn(String columnId, SFunction<File, ?> column, List<File> files) {
        deleteObject(files);
    }

    /**
     * 删除文件对象
     * @param files
     */
    private void deleteObject(List<File> files) {
        if (isEmpty(files)) {
            return;
        }
        for (File file : files) {
            boolean result = false;
            for (ApiCloudStorageService apiCloudStorageService : apiCloudStorageServices) {
                if (apiCloudStorageService.support(file.getStorageType())) {
                    result = apiCloudStorageService.delete(file.getObjectName());
                    if (!result) {
                        throw new BusinessException("删除文件对象失败", false, file);
                    }
                    break;
                }
            }
        }
    }
}
